package com.dxp.demo2.hikaircp;

import com.dxp.JdbcConfig;
import com.zaxxer.hikari.HikariDataSource;

import java.sql.Connection;
import java.sql.SQLException;

/**
 * @author carzy
 * @date 2018/11/12
 */
public class DataConfig {

    private static final String DRIVER_CLASS_NAME = JdbcConfig.DRIVER_CLASS_NAME;
    private static final String URL = JdbcConfig.URL;
    private static final String USERNAME = JdbcConfig.USERNAME;
    private static final String PASSWORD = JdbcConfig.PASSWORD;

    private static DataConfig dataConfig;
    private static HikariDataSource dataSource;

    public static DataConfig getInstance() {
        if (dataConfig == null) {
            synchronized (DataConfig.class) {
                dataConfig = new DataConfig();
            }
        }
        return dataConfig;
    }

    private DataConfig() {
    }

    private void initDataSource() {
        dataSource = new HikariDataSource();
        dataSource.setDriverClassName(DRIVER_CLASS_NAME);
        dataSource.setJdbcUrl(URL);
        dataSource.setUsername(USERNAME);
        dataSource.setPassword(PASSWORD);
        dataSource.setConnectionTimeout(30000);
        // 最大连接数目
        dataSource.setMinimumIdle(1);
        dataSource.setMaximumPoolSize(10);
        dataSource.setReadOnly(true);
    }

    public HikariDataSource getDataSource() {
        if (dataSource == null) {
            synchronized (DataConfig.class) {
                if (dataSource == null) {
                    initDataSource();
                }
            }
        }
        return dataSource;
    }

    public Connection getConnection() {
        try {
            return this.getDataSource().getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    public void close() {
        this.getDataSource().close();
    }
}
